from typing import List, Dict, Any

from autogen_core import CancellationToken

from mcp_tools.DataBaseMcp import DataBaseMcp, DummyParams, DatabaseType


class McpToolManager:
    """MCP工具管理器"""

    def __init__(self):
        self.tools: List[Any] = []
        self.tool_map: Dict[str, Any] = {}
        self._initialized = False
        self.db_mcp = None

    async def initialize(self):
        """初始化所有MCP工具"""
        if self._initialized:
            return

        try:
            # 初始化数据库MCP工具
            self.db_mcp = DataBaseMcp(db_type=DatabaseType.MYSQL)
            db_tools = await self.db_mcp.init_tools()

            # 将工具添加到管理器
            for tool in db_tools:
                self.tools.append(tool)
                self.tool_map[tool.name] = tool
                print(f"已加载MCP工具: {tool.name} - {tool.description}")

            self._initialized = True
            print(f"成功初始化 {len(self.tools)} 个MCP工具")

        except Exception as e:
            print(f"MCP工具初始化失败: {str(e)}")
            raise

    async def get_tools(self) -> List[Any]:
        """获取所有可用的MCP工具"""
        if not self._initialized:
            await self.initialize()
        return self.tools

    async def get_tool_by_name(self, tool_name: str) -> Any:
        """根据名称获取特定工具"""
        if not self._initialized:
            await self.initialize()
        return self.tool_map.get(tool_name)

    async def execute_tool(self, tool_name: str, params: Dict[str, Any], cancellation_token: CancellationToken) -> Any:
        """执行指定的MCP工具"""
        tool = await self.get_tool_by_name(tool_name)
        if not tool:
            raise ValueError(f"未找到工具: {tool_name}")

        try:
            result = await tool.run(params, cancellation_token)
            return result
        except Exception as e:
            print(f"执行工具 {tool_name} 失败: {str(e)}")
            raise

    async def query_database_tables(self, cancellation_token: CancellationToken) -> str:
        """查询数据库表结构"""
        try:
            # 使用DummyParams查询表结构
            if self.tools:
                tool = self.tools[0]

                # 首先查询所有表
                params = DummyParams(sql="SHOW TABLES;")
                tables_result = await tool.run(params, cancellation_token)

                # 提取表名列表
                table_names = []
                for table_result in tables_result:
                    if hasattr(table_result, 'text'):
                        table_name = table_result.text.strip()
                        if table_name:
                            table_names.append(table_name)

                # 返回简单的表名列表
                if table_names:
                    return "数据库中的表: " + ", ".join(table_names)
                else:
                    return "未找到任何表"
            else:
                return "无可用数据库工具"
        except Exception as e:
            return f"查询表结构失败: {str(e)}"

    async def execute_sql_query(self, sql: str, cancellation_token: CancellationToken) -> Any:
        """执行SQL查询"""
        try:
            if self.tools:
                tool = self.tools[0]  # 假设第一个工具是SQL执行工具
                params = DummyParams(sql=sql)
                result = await tool.run(params, cancellation_token)
                return result
            else:
                return None
        except Exception as e:
            print(f"SQL执行失败: {str(e)}")
            return None

    def get_database_type(self) -> str:
        """获取数据库类型"""
        if self.db_mcp:
            return self.db_mcp.gettype()
        return "unknown"

    def get_sql_syntax_info(self) -> Dict[str, Any]:
        """获取SQL语法信息"""
        if self.db_mcp:
            return self.db_mcp.get_sql_syntax_info()
        return {
            "type": "unknown",
            "date_format": "YYYY-MM-DD",
            "datetime_format": "YYYY-MM-DD HH:MM:SS",
            "string_quote": "'",
            "identifier_quote": "\"",
            "limit_syntax": "LIMIT",
            "offset_syntax": "OFFSET"
        }

    def get_tool_descriptions(self) -> Dict[str, str]:
        """获取所有工具的描述信息"""
        descriptions = {}
        for tool in self.tools:
            descriptions[tool.name] = tool.description
        return descriptions


# 全局工具管理器实例
tool_manager = McpToolManager()


async def get_tool_manager() -> McpToolManager:
    """获取全局工具管理器实例"""
    if not tool_manager._initialized:
        await tool_manager.initialize()
    return tool_manager
